package com.yqg.education.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yqg.education.controller.dto.ImportQuestionDto;
import com.yqg.education.entity.Question;
import com.yqg.education.mapper.QuestionMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * projectName:xf-service1
 * author:zxf
 * time:2024/10/15 9:49
 * description:
 */
@Component
public class QuestionListener extends AnalysisEventListener<ImportQuestionDto> {

    @Resource
    private QuestionMapper questionMapper;

    @Override
    public void invoke(ImportQuestionDto importQuestionDto, AnalysisContext analysisContext) {
        Question question = new Question();
        BeanUtil.copyProperties(importQuestionDto, question, true);
        if (importQuestionDto.getQuestionType().equals("3")) {
            question.setChooseOption("{\"F\": \"错误\", \"T\": \"正确\"}");
            question.setAnswer("\"" + importQuestionDto.getAnswer() + "\"");
        } else if (importQuestionDto.getQuestionType().equals("2")) {
            question.setChooseOption("{\"A\": \"" + importQuestionDto.getOptionA() + "\", \"B\": \"" + importQuestionDto.getOptionB() + "\", \"C\": \"" + importQuestionDto.getOptionC() + "\", \"D\": \"" + importQuestionDto.getOptionD() + "\"}");
            char[] answer = importQuestionDto.getAnswer().toCharArray();
            String answerJson = "";
            for (int i = 0; i < answer.length; i++) {
                answerJson += answer[i];
                if (i + 1 != answer.length) {
                    answerJson += "\", \"";
                }
            }
            question.setAnswer("[\"" + answerJson + "\"]");
        } else if (importQuestionDto.getQuestionType().equals("1")) {
            question.setChooseOption("{\"A\": \"" + importQuestionDto.getOptionA() + "\", \"B\": \"" + importQuestionDto.getOptionB() + "\", \"C\": \"" + importQuestionDto.getOptionC() + "\", \"D\": \"" + importQuestionDto.getOptionD() + "\"}");
            question.setAnswer("\"" + importQuestionDto.getAnswer() + "\"");
        } else {
            question.setChooseOption("{}");
            String[] answers = importQuestionDto.getAnswer().split(",");
            String answerJson = "";
            for (int i = 0; i < answers.length; i++) {
                answerJson += answers[i];
                if (i + 1 != answers.length) {
                    answerJson += "\", \"";
                }
            }
            question.setAnswer("[\"" + answerJson + "\"]");
        }
        question.setCreateTime(LocalDateTime.now());
        question.setIsDelete(0);
        questionMapper.insert(question);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
